<template>
	<view class="gy-search">
		<view class="gy-search-box">
			<view class="gy-search-icon gy_icon_search"></view>
			<view v-if="readonly" class="gy-search-input input-placeholder" @click.stop="searchFn">
				{{ props.placeholder }}
			</view>
			<input v-else v-model="keywords" type="text" confirm-type="search" placeholder-class="input-placeholder"
				:placeholder="props.placeholder" @input="inputFn" @confirm="searchFn">
			<view class="gy-search-clear" v-if="isAbleClear" @click.stop="clearFn">
				<com-icon name="gy_icon_closes" :size="36" color="#999" />
			</view>
		</view>

		<view class="gy-search-action">
			<slot>
				<com-button v-if="showSearch" :type="props.btnType" :btnText="props.btnText" @click.stop="searchFn" />
			</slot>
		</view>

	</view>
</template>

<script lang="ts" setup>
	import {
		ref, watch
	} from "vue";

	const emits = defineEmits(["search", "update:modelValue"]);
	const props = defineProps({
		modelValue: {
			type: String,
			default: ""
		},
		placeholder: {
			type: String,
			default: "请搜索"
		},
		readonly: {
			type: Boolean,
			default: false
		},
		showSearch: {
			type: Boolean,
			default: true
		},
		btnType: {
			type: String,
			default: "primary"
		},
		btnText: {
			type: String,
			default: "搜索"
		},
		triggerInput: {
			type: Boolean,
			default: true
		},
		isAbleClear: {
			type: Boolean,
			default: false
		}
	});

	const keywords = ref("");

	watch(() => props.modelValue, () => {
		keywords.value = props.modelValue;
	})

	function inputFn() {
		if (props.triggerInput) {
			searchFn()
		}
	}

	function searchFn() {
		emits("update:modelValue", keywords.value);
		emits("search", keywords.value);
	}
	function clearFn() {
		keywords.value = ''
	}
</script>

<script lang="ts">
	export default {
		options: {
			multipleSlots: true,
			styleIsolation: 'shared',
			addGlobalClass: true,
			virtualHost: true
		}
	}
</script>

<style lang="scss" scoped>
	.gy-search {
		@include flex-center-center;
		padding: var(--gy-gap);
		background-color: #ffffff;

		.gy-search-box {
			height: 80rpx;
			flex: 1;
			@include flex-center-center;
			background-color: #f5f5f5;
			border-radius: 45rpx;
			padding: 0 var(--gy-gap);

			.gy-search-icon {
				font-size: var(--gy-font-size-medium);
				color: var(--gy-text-color-regular);
			}

			.gy-search-input,
			input {
				flex: 1;
				padding-left: 15rpx;
				font-size: var(--gy-font-size-base);
				line-height: var(--gy-font-size-base);
			}

			.gy-search-input {
				font-size: 32rpx;
			}

			.gy-search-inputbox {
				position: relative;

				.gy-search-clear {
					position: absolute;
					width: 36rpx;
					height: 36rpx;
					display: flex;
					align-items: center;
					justify-content: center;

				}
			}

		}

		.gy-search-action {
			:deep(.gy-button) {
				margin-left: 30rpx !important;
			}

			:deep(.gy-badge) {
				margin-left: 30rpx !important;
			}
		}
	}
</style>
